package com.scsj.supermarket.view.activity.mapmodel;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.AAComAdapter;
import com.scsj.supermarket.adapter.homeadapter.AAViewHolder;
import com.scsj.supermarket.utils.BaiduMapHelper;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.scsj.supermarket.view.activity.shopermodel.RegisterFirstStepActivity;

import java.util.List;

public class AddShopMarkActivity extends BaseActivity implements View.OnClickListener{

    private List<PoiInfo> poiList;
    private PoiInfo poiInfo;
    private double lon;
    private double lat;
    private LatLng centerPosition;
    private String province;
    private String city;
    private String name;
    private String country;
    private String street;
    private String streetNumber;
    private String business;
    private String district;
    private MapView mapView;
    private GeoCoder mGeoCoder;
    private String details;
    private TextView addressTv;
    private TextView addressDescTv;
    private BaiduMap mBaiduMap;
    private ImageView mImageView;
    private float zoom = 16;
    private AAComAdapter adapter;
    private LatLng location;
    private LinearLayout addressLayout;
    private Button confirmBtn;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener1 = new MyLocationListener1();
    public BDLocation mLocation;
    private RelativeLayout serchLayout;

    public static int GOBACKDATA= -1002;

    private BottomSheetDialog mBottomSheetDialog;
    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_shop_mark);
        initView();
        initData();
        initListener();
    }
    @Override
    protected void initView() {
        serchLayout= findViewById(R.id.rel_classify_search);
        String isAddresst= getIntent().getStringExtra("isAddressEdit");
        if (isAddresst.equals("isAddressEdit")){
            serchLayout.setVisibility(View.GONE);
        }else {
            serchLayout.setVisibility(View.VISIBLE);
        }

        mImageView = findViewById(R.id.imageView1);
        addressLayout = findViewById(R.id.address_layout);
        mapView= findViewById(R.id.bmapView);
        addressTv= findViewById(R.id.address_tv);
        addressDescTv= findViewById(R.id.address_desc_tv);
        confirmBtn= findViewById(R.id.commit_btn);
        mBaiduMap = mapView.getMap();
        mGeoCoder = GeoCoder.newInstance();
        mGeoCoder.setOnGetGeoCodeResultListener(listener2);

        final TranslateAnimation animation = new TranslateAnimation(0, 0,0,-50);
        animation.setInterpolator(new LinearInterpolator());
        animation.setDuration(200);//设置动画持续时间
        animation.setRepeatCount(0);//设置重复次数
        animation.setFillAfter(true);

        final TranslateAnimation animation2 = new TranslateAnimation(0, 0,-50,0);
        animation2.setInterpolator(new LinearInterpolator());
        animation2.setDuration(200);//设置动画持续时间
        animation2.setRepeatCount(0);//设置重复次数
        animation2.setFillAfter(true);


        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {
                // TODO Auto-generated method stub
                mImageView.startAnimation(animation);
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus arg0) {
                //滑动结束之后监听
                mImageView.startAnimation(animation2);
                Point point = new Point();
                int[] location = new int[2];
                mImageView.getLocationOnScreen(location);
                point.x = location[0]-mImageView.getWidth()/2;
                point.y = location[1];
                zoom = arg0.zoom;
                Log.e("TAG","zoom==> " + zoom);
                centerPosition = mBaiduMap.getProjection().fromScreenLocation(point);
                lon = centerPosition.longitude;
                lat = centerPosition.latitude;
                mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(centerPosition));
            }
            @Override
            public void onMapStatusChange(MapStatus arg0) {
            }
        });

        getLocation1();
    }

    @Override
    protected void initListener() {
        addressLayout.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    OnGetGeoCoderResultListener listener2 = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {

            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }
            //获取地理编码结果
        }
        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR|| result.getPoiList().size()==0) {
                Toast.makeText(AddShopMarkActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG).show();
                return;
            }
            poiList = result.getPoiList();
            poiInfo = poiList.get(0);
            details = poiInfo.address;
            addressTv.setText(poiInfo.name);
            addressDescTv.setText(poiInfo.address);

            /**
             * 传给后台的一些数据
             */
            lat=result.getLocation().latitude;
            lon=result.getLocation().longitude;
            country = result.getAddressDetail().district;
            street= result.getAddressDetail().street;
            streetNumber= result.getAddressDetail().streetNumber;
            province = result.getAddressDetail().province;
            business= result.getBusinessCircle();
            city = result.getAddressDetail().city;
            district= result.getAddressDetail().district;

            /**
             * 传给后台的一些数据
             */
        }
    };

    private void creatBottomSheetDialog(){
        WindowManager wm = this.getWindowManager();
        int height = wm.getDefaultDisplay().getHeight();

        //构造函数的第二个参数可以设置BottomSheetDialog的主题样式
        //mBottomSheetDialog = new BottomSheetDialog(this,R.style.MyBottomDialog);
        mBottomSheetDialog = new BottomSheetDialog(this);
        //导入底部reycler布局
        View view = LayoutInflater.from(this).inflate(R.layout.recycler_address, null, false);
        mBottomSheetDialog.setContentView(view);

        BottomSheetBehavior mBehavior = BottomSheetBehavior.from((View) view.getParent());
        //设置默认弹出高度为屏幕的0.4倍
        mBehavior.setPeekHeight((int) (0.4 * height));

        //设置点击dialog外部不消失
        mBottomSheetDialog.setCanceledOnTouchOutside(false);

        ListView listView= view.findViewById(R.id.listView);

        adapter = new AAComAdapter<PoiInfo>(this,R.layout.poiinfo_item,poiList) {
            @Override
            public void convert(AAViewHolder holder, final PoiInfo mt) {
                if (mt.name.equals(poiInfo.name)){
                    holder.setImgResourceId(R.id.right_iv,R.mipmap.red_center_point_ic);
                } else {
                    holder.setImgResourceId(R.id.right_iv,R.mipmap.map_search_item_normal);
                }
                holder.setText(R.id.name_tv,mt.name);
                holder.setText(R.id.hint_tv,mt.address);

                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        name = mt.name;
                        location = mt.location;
                        details = mt.address;
                        mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                                .location(mt.location));
                        Intent intent= new Intent();
                        intent.putExtra("address_name",name);
                        intent.putExtra("detail_address",details);

                        intent.putExtra("lat",lat);
                        intent.putExtra("lon",lon);
                        intent.putExtra("country",country);
                        intent.putExtra("street",street);
                        intent.putExtra("streetNumber",streetNumber);
                        intent.putExtra("province",province);
                        intent.putExtra("business",business);
                        intent.putExtra("city",city);
                        intent.putExtra("district",district);

                        AddShopMarkActivity.this.setResult(GOBACKDATA, intent);//RESULT_OK为自定义常量
                        finish();
                    }
                });
            }
        };
        adapter.setNotShowNoData();
        listView.setAdapter(adapter);
        mBottomSheetDialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.address_layout:
                //加载更多地址
                creatBottomSheetDialog();
                break;
            case R.id.commit_btn:
                //点击确定按钮
                String markName= poiInfo.name;
                String detailAddressInfo= poiInfo.address;
                Intent intent= new Intent();
                intent.putExtra("address_name",markName);
                intent.putExtra("detail_address",details);

                intent.putExtra("lat",lat);
                intent.putExtra("lon",lon);
                intent.putExtra("country",country);
                intent.putExtra("street",street);
                intent.putExtra("streetNumber",streetNumber);
                intent.putExtra("province",province);
                intent.putExtra("business",business);
                intent.putExtra("city",city);
                intent.putExtra("district",district);

                AddShopMarkActivity.this.setResult(GOBACKDATA, intent);//RESULT_OK为自定义常量
                finish();
                break;
        }
    }


    public class MyLocationListener1 implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            //获取定位结果
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());    //获取定位时间

            sb.append("\nerror code : ");
            sb.append(location.getLocType());    //获取类型类型

            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());    //获取纬度信息

            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());    //获取经度信息

            sb.append("\nradius : ");
            sb.append(location.getRadius());    //获取定位精准度

            if (location.getLocType() == BDLocation.TypeGpsLocation) {

                // GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());    // 单位：公里每小时

                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());    //获取卫星数

                sb.append("\nheight : ");
                sb.append(location.getAltitude());    //获取海拔高度信息，单位米

                sb.append("\ndirection : ");
                sb.append(location.getDirection());    //获取方向信息，单位度

                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息

                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                // 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息

                sb.append("\noperationers : ");
                sb.append(location.getOperators());    //获取运营商信息

                sb.append("\ndescribe : ");
                sb.append("网络定位成功");

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                // 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");

            } else if (location.getLocType() == BDLocation.TypeServerError) {

                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");

            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");

            }

            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());    //位置语义化信息

            List<Poi> list = location.getPoiList();    // POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            mLocation = location;
//            mCity.setText(location.getCity());
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            centerPosition = new LatLng(location.getLatitude(),location.getLongitude());
            lon = centerPosition.longitude;
            lat = centerPosition.latitude;
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(centerPosition)
                    .zoom(16)
                    .build();
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态
            mBaiduMap.setMapStatus(mMapStatusUpdate);
            mLocationClient.stop();
            mGeoCoder.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(centerPosition));
        }
    }
    protected void getLocation1(){
        mLocationClient = new LocationClient(this);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener1);
        initLocation();
        //注册监听函数
        if (mLocationClient.isStarted()) {
            mLocationClient.requestLocation();
        }else {
            mLocationClient.start();
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(0);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        BaiduMapHelper.closeClient();
        if (mBottomSheetDialog!=null&&mBottomSheetDialog.isShowing()){
            mBottomSheetDialog.dismiss();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mGeoCoder.destroy();
        mapView = null;
        BaiduMapHelper.closeClient();
        if (mBottomSheetDialog!=null&&mBottomSheetDialog.isShowing()){
            mBottomSheetDialog.dismiss();
        }
        super.onDestroy();
    }


}
